﻿using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using PMS.BLL;
using PMS.Entity;
using PMS.Resources;
using PMS.Win;
using PMS.Utils;
using PMS.ValidationRules;
using System.Collections.Generic;

namespace PMS.DanhMucChung
{
    public partial class ProductEntry : FormEntryBase
    {
        #region Constants
        private string NEW_String = Messages.GetString(Constants.NEW);
        private const string BINDING_PROPERTY = "EditValue";
        #endregion

        #region Private Members
        protected SanPhamBO m_Service;
        private List<ComboItemExp> m_UnitList;
        private List<ComboItemExp> m_CategoryList;
        #endregion

        #region Properties
        protected Entity.SanPham CurrentProductEntry
        {
            get
            {
                return base.Entity as Entity.SanPham;
            }
            set
            {
                base.Entity = value;
            }
        }
        #endregion

        #region Services
        public SanPhamBO Service
        {
            get
            {
                if (m_Service == null)
                {
                    m_Service = new SanPhamBO();
                }
                return m_Service;
            }
        }
        #endregion

        #region Constructors
        public ProductEntry(string functionID)
            : base(functionID)
        {
            InitializeComponent();
            Init();
            CanPrint = true;  //allow print list of products when Product form open
        }
        #endregion

        #region Init Data and Style
        private void Init()
        {
            InitData();
            InitStyle();
        }

        private void InitData()
        {
            loadDatasourceCbbCategory();
            loadDatasourceCbbUnit();
        }

        private void InitStyle()
        {
            bteCode.BackColor = REQUIRED_FIELD_COLOR;
            cbbUnit.BackColor = REQUIRED_FIELD_COLOR;
            cbbCategory.BackColor = REQUIRED_FIELD_COLOR;

            this.bteCode.Properties.MaxLength = 12;
            this.txtHoaChat.Properties.MaxLength = 100;
            this.txtBietDuoc.Properties.MaxLength = 100;
            this.txtHamLuong.Properties.MaxLength = 100;
            this.txtDangBaoChe.Properties.MaxLength = 150;
            this.txtQuyCach.Properties.MaxLength =100;
            this.txtSoDK.Properties.MaxLength = 20;
            this.txtXuatXu.Properties.MaxLength = 30;
            this.txtNhaSX.Properties.MaxLength = 50;
            this.txtNhaNK.Properties.MaxLength = 50;
            this.cbbUnit.Properties.MaxLength = 6;
            this.cbbCategory.Properties.MaxLength = 4;
            this.txtNotes.Properties.MaxLength = 200;

            cbbCategory.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            cbbUnit.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
        }
        #endregion

        #region override methods
        protected override void ClearData()
        {
            New();
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            if (this.CurrentProductEntry == null)
            {
                this.DoNew();
            }
        }

        protected override void BindingToControls(IBaseEntity entity)
        {
            base.BindingToControls(entity);

            this.bteCode.DataBindings.Clear();
            this.txtHoaChat.DataBindings.Clear();
            this.txtBietDuoc.DataBindings.Clear();
            this.txtHamLuong.DataBindings.Clear();
            this.txtDangBaoChe.DataBindings.Clear();
            this.txtQuyCach.DataBindings.Clear();
            this.txtSoDK.DataBindings.Clear();
            this.txtXuatXu.DataBindings.Clear();
            this.txtNhaSX.DataBindings.Clear();
            this.txtNhaNK.DataBindings.Clear();
            this.txtNotes.DataBindings.Clear();

            this.bteCode.DataBindings.Add(BINDING_PROPERTY, entity, SanPhamColumns.MaThuoc.ToString());
            this.txtHoaChat.DataBindings.Add(BINDING_PROPERTY, entity, SanPhamColumns.TenHoatChat.ToString());
            this.txtBietDuoc.DataBindings.Add(BINDING_PROPERTY, entity, SanPhamColumns.TenBietDuoc.ToString());
            this.txtHamLuong.DataBindings.Add(BINDING_PROPERTY, entity, SanPhamColumns.NongDoHamLuong.ToString());
            this.txtDangBaoChe.DataBindings.Add(BINDING_PROPERTY, entity, SanPhamColumns.DangBaoChe.ToString());
            this.txtQuyCach.DataBindings.Add(BINDING_PROPERTY, entity, SanPhamColumns.QuyCach.ToString());
            this.txtSoDK.DataBindings.Add(BINDING_PROPERTY, entity, SanPhamColumns.SoDangKy.ToString());
            this.txtXuatXu.DataBindings.Add(BINDING_PROPERTY, entity, SanPhamColumns.XuatXu.ToString());
            this.txtNhaSX.DataBindings.Add(BINDING_PROPERTY, entity, SanPhamColumns.NhaSX.ToString());
            this.txtNhaNK.DataBindings.Add(BINDING_PROPERTY, entity, SanPhamColumns.NhaNK.ToString());
            this.txtNotes.DataBindings.Add(BINDING_PROPERTY, entity, SanPhamColumns.GhiChu.ToString());

            SanPham sp = entity as SanPham;
            SetCategoryCbbData(sp.MaNH);
            SetUnitCbbData(sp.MaDonVi);
        }

        protected override void FocusFirtsControl()
        {
            base.FocusFirtsControl();
            this.bteCode.Focus();
        }

        protected override void InitValidationRules()
        {
            base.InitValidationRules();
            Validator validate = new Validator(ValidationProvider);
            validate.AddValidationRule(base.CreateNotEmptyValidationRule());
            SetValidator(validate, cbbUnit);
            SetValidator(validate, cbbCategory);
            SetValidator(validate, bteCode);
        }

        public override void New()
        {
            this.CurrentProductEntry = new Entity.SanPham
                {
                    MaDonVi = m_UnitList[0].ItemValue as string,
                    MaNH = m_CategoryList[0].ItemValue as string
                };           
            base.New();
        }

        protected override bool Save()
        {
            try
            {
                if (IsNew)
                {
                    CurrentProductEntry = Service.CreateSanPham(CurrentProductEntry);
                }
                else
                {
                    Service.UpdateSanPham(CurrentProductEntry);
                }
                return true;
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }
        }

        protected override bool Delete()
        {
            try
            {
                Service.DeleteSanPham(CurrentProductEntry);
                return true;
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }
        }

        public override void Cancel()
        {
            //your code here
            base.Cancel();
        }

        protected override void Print()
        {
            PMS.ReportViewer.SanPhamViewer form = new ReportViewer.SanPhamViewer();
            form.WindowState = FormWindowState.Maximized;
            form.StartPosition = FormStartPosition.CenterParent;
            form.ShowDialog();
        }

        protected override IBaseEntity GetEntity()
        {
            //need to get the latest record of the current Entity's ID or code then return it
            return base.GetEntity();
        }
        #endregion

        #region Lookups
        #endregion

        #region Form's function

        private void loadDatasourceCbbUnit()
        {
            DonViTinhs list = (new DonViTinhBO()).GetAllDonViTinh();
            m_UnitList = new List<ComboItemExp>();
            foreach (var item in list)
            {
                ComboItemExp tem = new ComboItemExp();
                tem.DisplayValue = item.TenDonVi;
                tem.ItemValue = item.MaDonVi;
                m_UnitList.Add(tem);
            }

            cbbUnit.Properties.Items.AddRange(m_UnitList);
        }

        private void SetUnitCbbData(string code)
        {
            cbbUnit.SelectedItem = m_UnitList.Find(o => o.ItemValue.ToString().Equals(code, StringComparison.CurrentCultureIgnoreCase));
        }

        private void loadDatasourceCbbCategory()
        {
            NhomHangs list = (new NhomHangBO()).GetAllNhomHang();
            m_CategoryList = new List<ComboItemExp>();
            foreach (var item in list)
            {
                ComboItemExp tem = new ComboItemExp();
                tem.DisplayValue = item.TenNH;
                tem.ItemValue = item.MaNH;
                m_CategoryList.Add(tem);
            }

            cbbCategory.Properties.Items.AddRange(m_CategoryList);
        }

        private void SetCategoryCbbData(string code)
        {
            cbbCategory.SelectedItem = m_CategoryList.Find(o => o.ItemValue.ToString().Equals(code, StringComparison.CurrentCultureIgnoreCase));
        }

        private void LoadObjectOnForm(string previousCode, string code, IBaseEntity ObjectLoad)
        {
            if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
            {
                if (IsNew)
                {
                    if (ObjectLoad != null)
                    {
                        if (IsDataChanged)
                        {
                            var result = ShowSaveConfimMessage();
                            if (result == DialogResult.Yes)
                            {
                                CurrentProductEntry.MaThuoc = previousCode;
                                if (!base.ValidateControls() || !Save())
                                {
                                    return;
                                }
                            }
                        }
                        Entity = ObjectLoad;
                        IsNew = false;
                        IsDataChanged = false;
                    }
                    else
                    {
                        CurrentProductEntry.MaThuoc = code;
                        Entity = CurrentProductEntry;
                        IsNew = true;//important
                        IsDataChanged = true;//important                        
                    }
                }
                else
                {
                    if (!IsDataChanged)
                    {
                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentProductEntry = new SanPham();
                            CurrentProductEntry.MaThuoc = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentProductEntry;
                            IsNew = true;//important
                            IsDataChanged = true;//important   
                        }
                    }
                    else
                    {
                        var result = ShowSaveConfimMessage();
                        if (result == DialogResult.Yes)
                        {
                            CurrentProductEntry.MaThuoc = previousCode;
                            if (!base.ValidateControls() || !Save())
                            {
                                return;
                            }
                        }

                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentProductEntry = new SanPham();
                            CurrentProductEntry.MaThuoc = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentProductEntry; ;
                            IsNew = true;//important
                            IsDataChanged = true;//important 
                        }
                    }
                }
                ClearErrorMessage();
            }
        }
        #endregion

        private void bteCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                var form = new ProductLookup();
                if (form.ShowDialog() == DialogResult.OK)
                {
                    IsNew = false;
                    if (form.ProductSelected != null)
                    {
                        LoadObjectOnForm(bteCode.Text.Trim(), form.ProductSelected.MaThuoc, form.ProductSelected);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void bteCode_Leave(object sender, EventArgs e)
        {
            try
            {
                
                    if (CurrentProductEntry == null) return;
                    string previousCode = DataConvertUltils.ToString(CurrentProductEntry.MaThuoc);
                    string code = DataConvertUltils.ToString(bteCode.EditValue);
                    if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
                    {
                        SanPham temCustomer = Service.GetSanPhamByID(code);
                        LoadObjectOnForm(previousCode, code, temCustomer);
                    }
                
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void cbbUnit_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cbbUnit.SelectedItem != null)
            {
                CurrentProductEntry.MaDonVi = (cbbUnit.SelectedItem as ComboItemExp).ItemValue as string;
            }
        }

        private void cbbCategory_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cbbCategory.SelectedItem != null)
            {
                CurrentProductEntry.MaNH = (cbbCategory.SelectedItem as ComboItemExp).ItemValue as string;
            }
        }

        //private void bteUnit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        //{
        //    try
        //    {
        //        var form = new UnitLookup();
        //        if (form.ShowDialog() == DialogResult.OK)
        //        {
        //            if (form.UnitSelected != null)
        //            {
        //                CurrentProductEntry.MaDonVi = form.UnitSelected.MaDonVi;
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        ShowErrorMessage(ex);
        //    }
        //}

        //private void bteCategory_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        //{
        //    try
        //    {
        //        var form = new CategoryLookup();
        //        if (form.ShowDialog() == DialogResult.OK)
        //        {
        //            if (form.CategorySelected != null)
        //            {
        //                CurrentProductEntry.MaNH = form.CategorySelected.MaNH;
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        ShowErrorMessage(ex);
        //    }
        //}

        //private void bteUnit_Leave(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        string code = DataConvertUltils.ToString(cbbUnit.EditValue);
        //        DonViTinh nh = (new DonViTinhBO()).GetDonViTinhByID(code);
        //        if (nh != null)
        //        {
        //            CurrentProductEntry.MaDonVi = nh.MaDonVi;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        ShowErrorMessage(ex);
        //    }
        //}

        //private void bteCategory_Leave(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        string code = DataConvertUltils.ToString(cbbCategory.EditValue);
        //        NhomHang nh = (new NhomHangBO()).GetNhomHangByID(code);
        //        if (nh != null)
        //        {
        //            CurrentProductEntry.MaNH = nh.MaNH;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        ShowErrorMessage(ex);
        //    }
        //}


    }
}
